let userMap = new Map();
var libPath = projectType == 3 ? '../lib/' : '../../lib/';
layui.config({
    base: libPath //配置 layui 第三方扩展组件存放的基础目录
}).extend({
    locationX: 'locationX',
    location: 'location'
});
layui.use(['element','table','form','layer','util','location'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        layer = layui.layer;
    let location = layui.location;

    let CHARGE_URL = null;//收费

    getDomain();

    function getDomain() {
        $.get("/cdyardmgr/cdyardmgrMyYard/getDomain", {}, function (result) {
            if(result != null){
                if(result.data != null){
                    let domain = result.data;
                    CHARGE_URL = domain + "/static/gzh/index.html";
                    //RC_URL = domain + "/web/weixin/rcTest";
                    //CC_URL = domain + "/web/weixin/ccTest";
                }
            }
        });
    }

    queryDeviceCount("");

    function queryDeviceCount(projectId) {
        $.get("/cdyardmgr/cdyardmgrMyYard/queryDeviceCount", {type:projectType,projectId:projectId}, function (result) {
            if(result != null){
                if(result.data != null){
                    let dataMap = result.data;
                    if(projectId){
                        $("#sbzx").empty().append(dataMap.onlineCount);
                    }else {
                        $("#onlineDevice").empty().append(dataMap.onlineCount);
                        $("#allDevice").empty().append(dataMap.allCount);
                    }
                }
            }
        });
    }

    // 自己维护初始化标注。这里给的是成都市政府
    var locationData = {lng:104.07253,lat:30.579126};

    location.render("#locationBtn",{
        type:1,
        apiType: "baiduMap",
        coordinate: "baiduMap",
        mapType: 2,
        zoom: 15,
        title: '区域定位',
        init: function(){
            return {longitude: $("#longitude").val()?$("#longitude").val():locationData.lng,latitude: $("#latitude").val()?$("#latitude").val():locationData.lat};
        },
        success: function (data) { //只有经纬度
            showPosition(data);
        }
    });

    function showPosition(data){
        var url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=ltGX9ap4n4tYvEjYuNTNC76ZamxX7e5s&output=json&coordtype=wgs84ll&location="+data.lat+","+data.lng;
        $.ajax({
            type:  "GET" ,
            dataType:  "jsonp" ,
            url: url,
            beforeSend: function (){
            },
            success:  function  (json) {
                console.log(json);
                if(json.status === 0){
                    $("#locationName").val(json.result.formatted_address);
                }
            },
            error:  function  (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg("地址位置获取失败",{icon:5});
            }
        });
    }

    form.verify({
        carNum: function(value, item){
            var min = item.getAttribute('min-len');
            var max = item.getAttribute('max-len');
            if(value.length < Number(min) || value.length > Number(max) ){
                return '车牌号是6位或7位';
            }
        }
    });

    table.render({
        elem: '#myYardTable'
        ,url:'/cdsideparkmgr/cdsideparkmgrMyProject/list'
        ,title: '车场管理'
        ,where: {"projectType":projectType}
        ,cols: [[
            {field: 'xh',type:'numbers', title: '序号',}
            ,{field:'projectNo', title:'项目编号',align:'center'}
            ,{field:'projectName', title:'项目名称',align:'center'}
            ,{field:'carNum', title:'车位总数',align:'center'}
            ,{field:'onlineDevice', title:'在线设备',align:'center'}
            ,{field:'managerName', title:'车场负责人',align:'center'}
            ,{field:'managerPhone', title:'联系电话',align:'center'}
            ,{field:'sfgz', title:'收费规则',align:'center'}
            ,{field:'addressDetail', title:'项目位置',align:'center'}
            ,{ field: "projectStatus", align: "center", title: "是否启用",templet:function (d) {
                    return parseStatus(d.projectStatus);
                }}
            ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',fixed: 'right',width:420}
        ]]
        ,page: true
    });

    table.on('tool(myYardTable)',function (obj) {
        var data = obj.data;
        var yardId = data.id;
        switch (obj.event) {
            case 'detail':
                $("#projectId").val(yardId);
                renderForm(data);
                queryDeviceCount(yardId);
                $.get('/cdsideparkmgr/cdsideparkmgrMyProject/detail', {"id":yardId}, function (result) {
                    if(result != null){
                        if(result.data != null){
                            $("#chargeRule").html(result.data.rule);
                            form.render('select');
                        }
                    }
                });
                renderLockTable(yardId);
                layer.open({
                    type: 1
                    , title: '项目详情'
                    , shadeClose: true
                    , area: ['70%', '99%']
                    , content: $('#yardDiv')
                });
                break;
            case 'edit':
                $("#updateYardForm").attr("disabled", false);
                $("#updateYardForm").attr("class", "layui-btn");
                $("#id").val(yardId);
                $("#projectName").val(data.projectName);
                $("#locationName").val(data.addressDetail);
                $("#carNum").val(data.carNum);
                $("#managerName").val(data.managerName);
                $("#managerPhone").val(data.managerPhone);
                $("#kfdh").val(data.managerPhone);
                $("#projectDesc").val(data.projectDesc);
                $("#wxzf").val(data.wxzf);
                $("#blzf").val(data.blzf);
                $("#ppzf").val(data.ppzf);
                $("#qyzfjg").val(data.qyzfjg);
                form.render();
                layer.open({
                    type: 1
                    , title: '编辑项目信息'
                    , shadeClose: true
                    , area: ['60%', '99%']
                    , content: $('#addCarDiv')
                });
                break;
            case 'employee':
                $("#yardId").val(yardId);
                table.render({
                    elem: '#employeeTable'
                    ,url:'/cdyardmgr/cdyardmgrMyYard/listEmployee'
                    ,title: '员工管理'
                    ,where: {"yardId":yardId}
                    ,cols: [[
                        {field: 'xh',type:'numbers', title: '序号',}
                        ,{field:'role', title:'角色',align:'center'}
                        ,{field:'userName', title:'人员',align:'center'}
                        ,{field:'right',title:'操作',toolbar:'#barOperate2',align:'center',fixed: 'right'}
                    ]]
                });
                layer.open({
                    type: 1
                    , title: '车场员工'
                    , shadeClose: true
                    , area: ['99%', '99%']
                    , content: $('#employeeMgrDiv')
                    ,btn: ['确定', '取消']
                });
                break;
            case 'charge':
                $("#ruleYardId").val(yardId);
                loadRuleList(yardId);
                $("#addCharge").attr("disabled", false);
                $("#addCharge").attr("class", "layui-btn");
                // form.render();
                layer.open({
                    type: 1
                    , title: '收费规则配置'
                    , shadeClose: true
                    , area: ['40%', '50%']
                    , content: $('#chargeConfigDiv')
                });
                break;

        }
    });

    function renderLockTable(projectId) {
        table.render({
            elem: '#lockTable'
            ,url:'/cdsideparkmgr/cdsideparkmgrMyProject/listLock'
            ,title: '地锁车位列表'
            ,where: {"projectId":projectId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'lockName', title:'车位名称',align:'center',width:100}
                ,{field:'lockAddress', title:'安装地点',align:'center',width:100}
                ,{field:'lockArea', title:'所属区域',align:'center',width:100}
                ,{field:'lockMac', title:'地锁mac',align:'center',width:100}
                ,{field:'right',title:'操作',toolbar:'#barDownload',align:'center',fixed: 'right',width:100}
            ]]
            ,page: true
        });
    }

    table.on('tool(lockTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'download':
                let title = data.lockName+"[" + data.lockMac+"]收费二维码"
                $("#qrcodeLockTitle").val(title);
                generateQrcode("qrcodeDiv",CHARGE_URL+"?lockMac="+data.lockMac+"&proId="+data.projectId);
                layer.open({
                    type: 1
                    , title: title+'下载'
                    , shadeClose: true
                    , area: ['40%', '60%']
                    , content: $('#qrcodeDiv')
                });
                break;

        }
    });

    function loadRuleList(projectId) {
        $.get("/cdyardmgr/cdyardmgrMyYard/loadChargeRuleList", {}, function (result) {
            if(result != null){
                if(result.data != null){
                    var role_html = "<option value=''>请选择收费规则</option>";
                    $.each(result.data, function (index, item) {
                        role_html += "<option value='" + item.id + "'>" + item.name + "</option>";
                    });
                    $("#ruleId").empty().append(role_html);
                    $.get('/cdyardmgr/cdyardmgrMyYard/getRuleByYardId', {"yardId":projectId}, function (result) {
                        if(result != null){
                            if(result.data != null){
                                var select = 'dd[lay-value=' + result.data.ruleId + ']';
                                $('#ruleId').siblings("div.layui-form-select").find('dl').find(select).click();
                                // $("#ruleId").val(result.data.ruleId);
                                // form.render('select');
                            }
                        }
                    });
                    form.render('select');
                }
            }
        });
    }

    // 保存收费规则
    form.on('submit(addCharge)',function(data){
        layer.load();
        data.field.rule = $("#ruleId").find("option:selected").text();
        $.ajax({
            type: 'post',
            url: '/cdyardmgr/cdyardmgrMyYard/saveCharge',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                    table.reload('myYardTable');
                },1000);
            },
        });
        return false;
    });

    loadOptionList('/cdyardmgr/cdyardmgrMyYard/loadRoleList','请选择角色','roleId');
    loadOptionList('/cdyardmgr/cdyardmgrMyYard/loadUserList','请选择人员','userId');

    function loadOptionList(url,tip,eleId) {
        $.get(url, {}, function (result) {
            if(result != null){
                if(result.data != null){
                    var role_html = "<option value=''>"+tip+"</option>";
                    $.each(result.data, function (index, item) {
                        if(eleId == 'userId'){
                            userMap.set(item.id,item.userPhone);
                        }
                        role_html += "<option value='" + item.id + "'>" + item.name + "</option>";
                    });
                    $("#"+eleId).empty().append(role_html);
                    form.render('select');
                }
            }
        });
    }

    table.on('tool(employeeTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    var index = layer.load();
                    $.get('/cdyardmgr/cdyardmgrMyYard/deleteEmployee',{id:data.id},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                queryEmployee(data.yardId);
                                layer.close(index);
                            }
                        });
                    });
                });
                break;

        }
    });
    // 新增车场员工
    form.on('submit(addEmployee)',function(data){
        data.field.role = $("#roleId").find("option:selected").text();
        data.field.userName = $("#userId").find("option:selected").text();
        let userId = $("#userId").val();
        if(userId){
            data.field.userPhone = userMap.get(userId);
        }
        let index = layer.load();
        $.ajax({
            type: 'post',
            url: '/cdyardmgr/cdyardmgrMyYard/saveEmployee',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.close(index);
                },1000);
                table.reload('employeeTable');
            },
        });
        return false;
    });

    function queryEmployee(yardId){
        table.reload('employeeTable',{
            where: {yardId:yardId}
        });
    }

    function renderForm(data){
        $("#projectName2").html(data.projectName);
        $("#addressDetail").html(data.addressDetail);
        $("#carNum2").html(data.carNum);
        $("#managerName2").html(data.managerName);
        $("#kfdh2").html(data.managerPhone);
        $("#managerPhone2").html(data.managerPhone);
        $("#projectDesc2").html(data.projectDesc);
        $("#qyzfjg2").html(data.qyzfjg);
        $("#wxzf2").html(data.wxzf);
        $("#blzf2").html(data.blzf);
        $("#ppzf2").html(data.ppzf);
        //$("#chargeQrCode").attr("href","http://www.baidu.com");
        //$("#voiceQrCode").attr("href","http://www.baidu.com");
        form.render();
    }

    function queryYard(){
        var projectName = $("#searchName").val();
        var projectNo = $("#searchCode").val();
        table.reload('myYardTable',{
            where: {projectName:projectName,projectNo:projectNo,projectType:projectType}
            ,page:  {
                curr:1
            }
        });
    }
    form.on('submit(queryYard)',function () {
        queryYard();
        return false;
    });

    function queryLock(){
        var projectId = $("#projectId").val();
        var lockName = $("#lockName").val();
        table.reload('lockTable',{
            where: {projectId:projectId,lockName:lockName}
            ,page:  {
                curr:1
            }
        });
    }
    form.on('submit(queryLock)',function () {
        queryLock();
        return false;
    });

    form.on('submit(updateYardForm)',function(data){
        $("#updateYardForm").attr("disabled", true);
        $("#updateYardForm").attr("class", "layui-btn layui-btn-disabled");
        data.field.category = $("#categoryId").find("option:selected").text();
        layer.load();
        $.ajax({
            type: 'post',
            url: '/cdyardmgr/cdyardmgrMyYard/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#updateYardForm").attr("disabled", false);
                $("#updateYardForm").attr("class", "layui-btn");
                table.reload('myYardTable');
            },
        });
        return false;
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });

    $("#cancel_charge_form").on('click',function (){
        layer.closeAll();
        return false;
    });

    $("#chargeQrCode").on('click',function (){
        let yardId = $("#projectId").val();
        $("#qrcodeTitle").val("收费");
        generateQrcode("qrcodeShowDiv",CHARGE_URL+"?proId="+yardId);
        layer.open({
            type: 1
            , title: '收费二维码下载'
            , shadeClose: true
            , area: ['40%', '60%']
            , content: $('#qrcodeShowDiv')
        });
    });

    $("#voiceQrCode").on('click',function (){
        $("#qrcodeTitle").val("语音呼叫");
        generateQrcode("qrcodeShowDiv","语音呼叫二维码");
        layer.open({
            type: 1
            , title: '语音呼叫二维码下载'
            , shadeClose: true
            , area: ['40%', '60%']
            , content: $('#qrcodeShowDiv')
        });
    });

    $("#qrcodeDiv .download").on('click',function () {
        var imgUrl = $('#qrcodeDiv .qrcodeImg').attr('src');
        var imgName = $("#qrcodeLockTitle").val();
        downloadBase64Img(imgUrl,imgName);
    });

    function generateQrcode(eleId,qrcodeData) {
        $("#"+eleId).find(".qrcode").html("");
        var url4 = str2utf8(qrcodeData);
        /* 生成二维码 */
        var qrcode= $("#"+eleId).find(".qrcode").qrcode({
            render: "canvas",            //设置渲染方式
            width: 180,                  //设置宽度,默认生成的二维码大小是 256×256
            height: 180,                 //设置高度
            typeNumber: -1,                 //计算模式
            background: "#ffffff",          //背景颜色
            foreground: "black",             //前景颜色（粉色）
            correctLevel:0,
            text: url4                      //设置二维码内容
        });
        var canvas=qrcode.find('canvas').get(0);
        $("#"+eleId).find(".qrcodeImg").attr('src',canvas.toDataURL('image/jpg'));
    }

    function downloadBase64Img(imgUrl,imgName) {
        if(!imgUrl){
            layer.msg("二维码不存在",{icon:5});
            return false;
        }
        // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
            var bstr = atob(imgUrl.split(',')[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            var blob = new Blob([u8arr]);
            window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png');
        } else {
            // 这里就按照chrome等新版浏览器来处理
            const a = document.createElement('a');
            a.href = imgUrl;
            a.setAttribute('download', imgName);
            a.click();
        }
    }

    $("#sbqk").on('click',function () {
        table.render({
            elem: '#deviceTable'
            ,url:'/cdyardmgr/cdyardmgrMyYard/listDevice'
            ,title: '设备在线详情'
            ,where: {"type":projectType}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'projectName', title:'车场名称',align:'center'}
                ,{field:'deviceName', title:'设备名称',align:'center'}
                ,{field:'deviceMac', title:'设备mac',align:'center'}
                ,{ field: "isOnline", align: "center", title: "是否在线",templet:function (d) {
                        return parseState(d.isOnline);
                    }}
            ]]
        });
        layer.open({
            type: 1
            , title: '设备详情'
            , shadeClose: true
            , area: ['99%', '99%']
            , content: $('#sbqkDiv')
            ,btn: ['确定', '取消']
        });
    });

    form.on('submit(queryDevice)', function (data) {
        data.field.type = projectType;
        table.reload('deviceTable',{
            where: data.field
            ,page: {curr:1}
        });
        return false;
    });

});

/* 解决中文乱码 */
function str2utf8(str){
    // UCS-2和UTF8都是unicode的一种编码方式
    // js代码中使用的是UCS-2编码
    var code;
    var utf = "";

    for (var i = 0; i < str.length; i++){
        code = str.charCodeAt(i);//返回每个字符的Unicode 编码
        if (code < 0x0080) {
            utf += str.charAt(i);//返回指定位置的字符
        }else if (code < 0x0800) {
            utf += String.fromCharCode(0xC0 | ((code >> 6) & 0x1F));
            utf += String.fromCharCode(0x80 | ((code >> 0) & 0x3F));
        }else if (code < 0x10000) {
            utf += String.fromCharCode(0xE0 | ((code >> 12) & 0x0F));
            utf += String.fromCharCode(0x80 | ((code >>  6) & 0x3F));
            utf += String.fromCharCode(0x80 | ((code >>  0) & 0x3F));
        }else{
            throw "不是UCS-2字符集"
        }
    }
    return utf;
}
function parseState(state) {
    if(!state){return "-";}
    switch (Number(state)) {
        case 1: return '是';
        case 2: return '否';
        default: return '-';
    }
}
function parseStatus(state) {
    if(!state){return "-";}
    switch (Number(state)) {
        case 1: return '否';
        case 2: return '是';
        default: return '-';
    }
}